package com.nuoniu.sibanyun.service.production.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.entity.production.ErpMrpProgramme;
import com.nuoniu.sibanyun.mapper.production.ErpMrpProgrammeMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.production.IErpMrpProgrammeService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * mrp运算方案 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-03-16
 */
@Service
public class ErpMrpProgrammeServiceImpl extends ServiceImpl<ErpMrpProgrammeMapper, ErpMrpProgramme> implements IErpMrpProgrammeService {

    @Autowired
    private IErpAccountService accountService;

    @Override
    public Page<ErpMrpProgramme> getProgrammeList(Page page, ErpMrpProgramme mrpProgramme) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<ErpMrpProgramme> queryWrapper = new QueryWrapper();
        queryWrapper.eq("company_id", userInfo.getCompanyId());
        queryWrapper.or(wrapper -> wrapper.eq("is_system", 1));
        queryWrapper.orderByAsc("company_id, code");
        return page(page, queryWrapper);
    }

    @Override
    public void saveMrpProgramme(ErpMrpProgramme mrpProgramme) {
        UserInfo userInfo = UserThreadLocal.get();
        ErpMrpProgramme programmeByName = baseMapper.getByName(userInfo.getCompanyId(), mrpProgramme.getName());
        ErpMrpProgramme programmeByCode = baseMapper.getByCode(userInfo.getCompanyId(), mrpProgramme.getCode());
        if(mrpProgramme.getId() == null) {
            mrpProgramme.setAccountId(accountService.getCurrentAccountId());
            mrpProgramme.setCompanyId(userInfo.getCompanyId());
            if(programmeByName != null) {
                throw new NuoNiuException("方案名称已存在");
            }
            if(programmeByCode != null) {
                throw new NuoNiuException("方案编码已存在");
            }
        }else {
            if(programmeByName != null && !programmeByName.getId().equals(mrpProgramme.getId())) {
                throw new NuoNiuException("方案名称已存在");
            }
            if(programmeByCode != null && !(programmeByCode.getId().equals(mrpProgramme.getId()))) {
                throw new NuoNiuException("方案编码已存在");
            }
        }
        saveOrUpdate(mrpProgramme);
    }
}
